<template>
  <div class="settings-management">
    <div class="page-header">
      <h1 class="page-title">系统设置</h1>
      <div class="header-actions">
        <el-button :icon="Download" @click="handleExportSettings">
          导出设置
        </el-button>
        <el-button :icon="Upload" @click="showImportDialog = true">
          导入设置
        </el-button>
        <el-button :icon="Refresh" @click="handleRefreshStatus">
          刷新状态
        </el-button>
      </div>
    </div>

    <!-- 系统状态卡片 -->
    <el-row :gutter="20" class="status-cards" v-if="systemStatus">
      <el-col :span="6">
        <el-card class="status-card">
          <div class="status-content">
            <div class="status-icon server">
              <el-icon><Monitor /></el-icon>
            </div>
            <div class="status-info">
              <div class="status-title">服务器状态</div>
              <div class="status-value" :class="systemStatus.server.status">
                {{ systemStatus.server.status === 'running' ? '运行中' : '已停止' }}
              </div>
              <div class="status-detail">运行时间: {{ systemStatus.server.uptime }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="status-card">
          <div class="status-content">
            <div class="status-icon database">
              <el-icon><Coin /></el-icon>
            </div>
            <div class="status-info">
              <div class="status-title">数据库</div>
              <div class="status-value" :class="systemStatus.database.status">
                {{ systemStatus.database.status === 'running' ? '运行中' : '已停止' }}
              </div>
              <div class="status-detail">连接数: {{ systemStatus.database.connections }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="status-card">
          <div class="status-content">
            <div class="status-icon resource">
              <el-icon><PieChart /></el-icon>
            </div>
            <div class="status-info">
              <div class="status-title">系统资源</div>
              <div class="status-value">CPU: {{ systemStatus.server.cpu }}</div>
              <div class="status-detail">内存: {{ systemStatus.server.memory }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="status-card">
          <div class="status-content">
            <div class="status-icon storage">
              <el-icon><Files /></el-icon>
            </div>
            <div class="status-info">
              <div class="status-title">存储空间</div>
              <div class="status-value">{{ systemStatus.server.disk }}</div>
              <div class="status-detail">数据库: {{ systemStatus.database.size }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 设置标签页 -->
    <el-card shadow="never" class="settings-card">
      <el-tabs v-model="activeTab" tab-position="left" class="settings-tabs">
        <!-- 医院信息 -->
        <el-tab-pane label="医院信息" name="hospital">
          <div class="settings-section">
            <h3>基本信息</h3>
            <el-form
              ref="hospitalFormRef"
              :model="settingsForm.hospital"
              :rules="hospitalRules"
              label-width="120px"
            >
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="医院名称" prop="name">
                    <el-input v-model="settingsForm.hospital.name" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="医院编码" prop="code">
                    <el-input v-model="settingsForm.hospital.code" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="医院级别" prop="level">
                    <el-select v-model="settingsForm.hospital.level">
                      <el-option label="三甲医院" value="三甲医院" />
                      <el-option label="三乙医院" value="三乙医院" />
                      <el-option label="二甲医院" value="二甲医院" />
                      <el-option label="二乙医院" value="二乙医院" />
                      <el-option label="一甲医院" value="一甲医院" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="院长" prop="director">
                    <el-input v-model="settingsForm.hospital.director" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-form-item label="医院地址" prop="address">
                <el-input v-model="settingsForm.hospital.address" />
              </el-form-item>

              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="联系电话" prop="phone">
                    <el-input v-model="settingsForm.hospital.phone" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="传真" prop="fax">
                    <el-input v-model="settingsForm.hospital.fax" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="邮箱" prop="email">
                    <el-input v-model="settingsForm.hospital.email" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="网站" prop="website">
                    <el-input v-model="settingsForm.hospital.website" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="成立时间" prop="established">
                    <el-date-picker
                      v-model="settingsForm.hospital.established"
                      type="date"
                      placeholder="选择日期"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="床位数" prop="beds">
                    <el-input-number v-model="settingsForm.hospital.beds" :min="0" style="width: 100%" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="科室数" prop="departments">
                    <el-input-number v-model="settingsForm.hospital.departments" :min="0" style="width: 100%" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-form-item label="医院简介">
                <el-input
                  v-model="settingsForm.hospital.description"
                  type="textarea"
                  :rows="4"
                  placeholder="请输入医院简介"
                />
              </el-form-item>

              <el-form-item>
                <el-button type="primary" @click="handleSaveSection('hospital')" :loading="loading">
                  保存设置
                </el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>

        <!-- 业务设置 -->
        <el-tab-pane label="业务设置" name="business">
          <div class="settings-section">
            <h3>工作时间</h3>
            <el-form label-width="120px">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="工作日">
                    <el-time-picker
                      v-model="workdayTime"
                      is-range
                      range-separator="至"
                      start-placeholder="开始时间"
                      end-placeholder="结束时间"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="周末">
                    <el-time-picker
                      v-model="weekendTime"
                      is-range
                      range-separator="至"
                      start-placeholder="开始时间"
                      end-placeholder="结束时间"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-form-item label="节假日">
                <el-switch
                  v-model="settingsForm.business.workingHours.holidays"
                  active-text="营业"
                  inactive-text="休息"
                />
              </el-form-item>
            </el-form>

            <el-divider />

            <h3>预约设置</h3>
            <el-form label-width="120px">
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="提前预约天数">
                    <el-input-number
                      v-model="settingsForm.business.appointmentSettings.advanceBookingDays"
                      :min="1"
                      :max="365"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="每日最大预约数">
                    <el-input-number
                      v-model="settingsForm.business.appointmentSettings.maxAppointmentsPerDay"
                      :min="1"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="取消截止时间(小时)">
                    <el-input-number
                      v-model="settingsForm.business.appointmentSettings.cancellationDeadline"
                      :min="1"
                      :max="48"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-form-item label="提醒设置">
                <el-switch
                  v-model="settingsForm.business.appointmentSettings.reminderSettings.enabled"
                  active-text="启用提醒"
                  inactive-text="禁用提醒"
                />
              </el-form-item>

              <div v-if="settingsForm.business.appointmentSettings.reminderSettings.enabled">
                <el-form-item label="提前提醒时间">
                  <el-input-number
                    v-model="settingsForm.business.appointmentSettings.reminderSettings.advanceHours"
                    :min="1"
                    :max="72"
                    style="width: 200px"
                  />
                  <span style="margin-left: 8px">小时</span>
                </el-form-item>

                <el-form-item label="提醒方式">
                  <el-checkbox-group v-model="settingsForm.business.appointmentSettings.reminderSettings.methods">
                    <el-checkbox label="短信">短信</el-checkbox>
                    <el-checkbox label="微信">微信</el-checkbox>
                    <el-checkbox label="邮件">邮件</el-checkbox>
                    <el-checkbox label="电话">电话</el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
              </div>
            </el-form>

            <el-button type="primary" @click="handleSaveSection('business')" :loading="loading">
              保存设置
            </el-button>
          </div>
        </el-tab-pane>

        <!-- 安全设置 -->
        <el-tab-pane label="安全设置" name="security">
          <div class="settings-section">
            <h3>密码策略</h3>
            <el-form label-width="140px">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="密码最小长度">
                    <el-input-number
                      v-model="settingsForm.security.passwordPolicy.minLength"
                      :min="6"
                      :max="20"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="密码过期天数">
                    <el-input-number
                      v-model="settingsForm.security.passwordPolicy.expirationDays"
                      :min="0"
                      :max="365"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-form-item label="密码复杂度要求">
                <el-checkbox-group>
                  <el-checkbox v-model="settingsForm.security.passwordPolicy.requireUppercase">
                    必须包含大写字母
                  </el-checkbox>
                  <el-checkbox v-model="settingsForm.security.passwordPolicy.requireLowercase">
                    必须包含小写字母
                  </el-checkbox>
                  <el-checkbox v-model="settingsForm.security.passwordPolicy.requireNumbers">
                    必须包含数字
                  </el-checkbox>
                  <el-checkbox v-model="settingsForm.security.passwordPolicy.requireSpecialChars">
                    必须包含特殊字符
                  </el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-form>

            <el-divider />

            <h3>会话设置</h3>
            <el-form label-width="140px">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="会话超时时间(分钟)">
                    <el-input-number
                      v-model="settingsForm.security.sessionSettings.timeoutMinutes"
                      :min="5"
                      :max="480"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="最大并发会话数">
                    <el-input-number
                      v-model="settingsForm.security.sessionSettings.maxConcurrentSessions"
                      :min="1"
                      :max="10"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>

            <el-divider />

            <h3>审计设置</h3>
            <el-form label-width="140px">
              <el-form-item label="启用审计日志">
                <el-switch
                  v-model="settingsForm.security.auditSettings.enabled"
                  active-text="启用"
                  inactive-text="禁用"
                />
              </el-form-item>

              <el-form-item label="日志保留天数" v-if="settingsForm.security.auditSettings.enabled">
                <el-input-number
                  v-model="settingsForm.security.auditSettings.retentionDays"
                  :min="30"
                  :max="1095"
                  style="width: 200px"
                />
                <span style="margin-left: 8px">天</span>
              </el-form-item>
            </el-form>

            <el-button type="primary" @click="handleSaveSection('security')" :loading="loading">
              保存设置
            </el-button>
          </div>
        </el-tab-pane>

        <!-- 系统维护 -->
        <el-tab-pane label="系统维护" name="system">
          <div class="settings-section">
            <h3>数据备份</h3>
            <el-form label-width="120px">
              <el-form-item label="自动备份">
                <el-switch
                  v-model="settingsForm.system.backup.enabled"
                  active-text="启用"
                  inactive-text="禁用"
                />
              </el-form-item>

              <div v-if="settingsForm.system.backup.enabled">
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="备份频率">
                      <el-select v-model="settingsForm.system.backup.frequency">
                        <el-option label="每日备份" value="daily" />
                        <el-option label="每周备份" value="weekly" />
                        <el-option label="每月备份" value="monthly" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="保留天数">
                      <el-input-number
                        v-model="settingsForm.system.backup.retentionDays"
                        :min="7"
                        :max="365"
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-form-item label="备份位置">
                  <el-input v-model="settingsForm.system.backup.location" />
                </el-form-item>
              </div>

              <el-form-item>
                <el-button type="primary" @click="handleBackup" :loading="backupLoading">
                  立即备份
                </el-button>
                <el-button @click="showRestoreDialog = true">
                  恢复数据
                </el-button>
              </el-form-item>
            </el-form>

            <el-divider />

            <h3>系统清理</h3>
            <el-form label-width="120px">
              <el-form-item label="清理选项">
                <el-checkbox-group v-model="cleanupOptions">
                  <el-checkbox label="logs">清理系统日志</el-checkbox>
                  <el-checkbox label="temp">清理临时文件</el-checkbox>
                  <el-checkbox label="backups">清理过期备份</el-checkbox>
                </el-checkbox-group>
              </el-form-item>

              <el-form-item label="保留天数">
                <el-input-number
                  v-model="cleanupDays"
                  :min="7"
                  :max="365"
                  style="width: 200px"
                />
                <span style="margin-left: 8px">天</span>
              </el-form-item>

              <el-form-item>
                <el-button type="warning" @click="handleCleanup" :loading="cleanupLoading">
                  开始清理
                </el-button>
              </el-form-item>
            </el-form>

            <el-button type="primary" @click="handleSaveSection('system')" :loading="loading">
              保存设置
            </el-button>
          </div>
        </el-tab-pane>

        <!-- 通知设置 -->
        <el-tab-pane label="通知设置" name="notifications">
          <div class="settings-section">
            <h3>邮件设置</h3>
            <el-form label-width="120px">
              <el-form-item label="启用邮件通知">
                <el-switch
                  v-model="settingsForm.system.notifications.email.enabled"
                  active-text="启用"
                  inactive-text="禁用"
                />
              </el-form-item>

              <div v-if="settingsForm.system.notifications.email.enabled">
                <el-row :gutter="20">
                  <el-col :span="16">
                    <el-form-item label="SMTP服务器">
                      <el-input v-model="settingsForm.system.notifications.email.server" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="端口">
                      <el-input-number v-model="settingsForm.system.notifications.email.port" style="width: 100%" />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="用户名">
                      <el-input v-model="settingsForm.system.notifications.email.username" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="密码">
                      <el-input type="password" v-model="settingsForm.system.notifications.email.password" />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-form-item label="SSL加密">
                  <el-switch v-model="settingsForm.system.notifications.email.ssl" />
                </el-form-item>

                <el-form-item>
                  <el-button @click="handleTestEmail" :loading="emailTestLoading">
                    测试邮件配置
                  </el-button>
                </el-form-item>
              </div>
            </el-form>

            <el-divider />

            <h3>短信设置</h3>
            <el-form label-width="120px">
              <el-form-item label="启用短信通知">
                <el-switch
                  v-model="settingsForm.system.notifications.sms.enabled"
                  active-text="启用"
                  inactive-text="禁用"
                />
              </el-form-item>

              <div v-if="settingsForm.system.notifications.sms.enabled">
                <el-form-item label="服务商">
                  <el-select v-model="settingsForm.system.notifications.sms.provider">
                    <el-option label="阿里云" value="aliyun" />
                    <el-option label="腾讯云" value="tencent" />
                    <el-option label="华为云" value="huawei" />
                  </el-select>
                </el-form-item>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="API Key">
                      <el-input v-model="settingsForm.system.notifications.sms.apiKey" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="API Secret">
                      <el-input type="password" v-model="settingsForm.system.notifications.sms.apiSecret" />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-form-item>
                  <el-button @click="handleTestSms" :loading="smsTestLoading">
                    测试短信配置
                  </el-button>
                </el-form-item>
              </div>
            </el-form>
          </div>
        </el-tab-pane>

        <!-- 界面设置 -->
        <el-tab-pane label="界面设置" name="interface">
          <div class="settings-section">
            <h3>显示设置</h3>
            <el-form label-width="120px">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="主题">
                    <el-select v-model="settingsForm.interface.theme">
                      <el-option label="浅色主题" value="light" />
                      <el-option label="深色主题" value="dark" />
                      <el-option label="跟随系统" value="auto" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="语言">
                    <el-select v-model="settingsForm.interface.language">
                      <el-option label="简体中文" value="zh-CN" />
                      <el-option label="繁体中文" value="zh-TW" />
                      <el-option label="English" value="en-US" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="日期格式">
                    <el-select v-model="settingsForm.interface.dateFormat">
                      <el-option label="YYYY-MM-DD" value="YYYY-MM-DD" />
                      <el-option label="YYYY/MM/DD" value="YYYY/MM/DD" />
                      <el-option label="DD/MM/YYYY" value="DD/MM/YYYY" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="时间格式">
                    <el-select v-model="settingsForm.interface.timeFormat">
                      <el-option label="24小时制" value="HH:mm" />
                      <el-option label="12小时制" value="hh:mm A" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="货币">
                    <el-select v-model="settingsForm.interface.currency">
                      <el-option label="人民币 (CNY)" value="CNY" />
                      <el-option label="美元 (USD)" value="USD" />
                      <el-option label="欧元 (EUR)" value="EUR" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="时区">
                    <el-select v-model="settingsForm.interface.timezone">
                      <el-option label="北京时间" value="Asia/Shanghai" />
                      <el-option label="香港时间" value="Asia/Hong_Kong" />
                      <el-option label="东京时间" value="Asia/Tokyo" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="每页显示数量">
                    <el-input-number
                      v-model="settingsForm.interface.pageSize"
                      :min="10"
                      :max="100"
                      :step="10"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="自动保存">
                    <el-switch
                      v-model="settingsForm.interface.autoSave"
                      active-text="启用"
                      inactive-text="禁用"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>

            <el-button type="primary" @click="handleSaveSection('interface')" :loading="loading">
              保存设置
            </el-button>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 导入设置对话框 -->
    <el-dialog v-model="showImportDialog" title="导入设置" width="500px">
      <el-upload
        class="upload-demo"
        drag
        :on-change="handleFileChange"
        :auto-upload="false"
        accept=".json"
      >
        <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
        <div class="el-upload__text">
          将配置文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            只能上传json格式的配置文件
          </div>
        </template>
      </el-upload>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showImportDialog = false">取消</el-button>
          <el-button type="primary" @click="handleImportSettings" :loading="importLoading">
            导入
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 恢复数据对话框 -->
    <el-dialog v-model="showRestoreDialog" title="恢复数据" width="500px">
      <el-form label-width="100px">
        <el-form-item label="备份文件">
          <el-select v-model="selectedBackupFile" placeholder="请选择备份文件">
            <el-option label="backup_2024-01-20.sql" value="backup_2024-01-20.sql" />
            <el-option label="backup_2024-01-19.sql" value="backup_2024-01-19.sql" />
            <el-option label="backup_2024-01-18.sql" value="backup_2024-01-18.sql" />
          </el-select>
        </el-form-item>
      </el-form>

      <el-alert
        title="警告"
        description="恢复数据将覆盖当前数据，请谨慎操作！"
        type="warning"
        show-icon
        :closable="false"
      />

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showRestoreDialog = false">取消</el-button>
          <el-button type="danger" @click="handleRestore" :loading="restoreLoading">
            确认恢复
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Download, Upload, Refresh, Monitor, Coin, PieChart, 
  Files, UploadFilled 
} from '@element-plus/icons-vue'
import { useSettingsStore } from '@/stores/modules/settings'

const settingsStore = useSettingsStore()

// 响应式数据
const activeTab = ref('hospital')
const loading = ref(false)
const backupLoading = ref(false)
const cleanupLoading = ref(false)
const emailTestLoading = ref(false)
const smsTestLoading = ref(false)
const importLoading = ref(false)
const restoreLoading = ref(false)

const showImportDialog = ref(false)
const showRestoreDialog = ref(false)

const systemStatus = ref<any>(null)
const selectedBackupFile = ref('')
const importFile = ref<File | null>(null)

// 清理选项
const cleanupOptions = ref(['logs', 'temp'])
const cleanupDays = ref(30)

// 表单数据
const settingsForm = reactive({
  hospital: {
    name: '',
    code: '',
    address: '',
    phone: '',
    fax: '',
    email: '',
    website: '',
    logo: '',
    description: '',
    director: '',
    established: '',
    level: '',
    beds: 0,
    departments: 0
  },
  business: {
    workingHours: {
      weekdays: { start: '08:00', end: '17:30' },
      weekends: { start: '08:00', end: '12:00' },
      holidays: false
    },
    appointmentSettings: {
      advanceBookingDays: 30,
      maxAppointmentsPerDay: 100,
      cancellationDeadline: 2,
      reminderSettings: {
        enabled: true,
        advanceHours: 24,
        methods: ['短信', '微信']
      }
    },
    paymentSettings: {
      methods: ['现金', '银行卡', '微信', '支付宝', '医保'],
      autoInvoice: true,
      taxRate: 0.06
    }
  },
  security: {
    passwordPolicy: {
      minLength: 8,
      requireUppercase: true,
      requireLowercase: true,
      requireNumbers: true,
      requireSpecialChars: false,
      expirationDays: 90
    },
    sessionSettings: {
      timeoutMinutes: 30,
      maxConcurrentSessions: 3
    },
    auditSettings: {
      enabled: true,
      retentionDays: 365
    }
  },
  system: {
    backup: {
      enabled: true,
      frequency: 'daily' as 'daily' | 'weekly' | 'monthly',
      retentionDays: 30,
      location: '/backup'
    },
    notifications: {
      email: {
        enabled: true,
        server: '',
        port: 587,
        username: '',
        password: '',
        ssl: true
      },
      sms: {
        enabled: true,
        provider: 'aliyun',
        apiKey: '',
        apiSecret: ''
      }
    },
    integrations: {
      his: { enabled: false, endpoint: '', apiKey: '' },
      lis: { enabled: false, endpoint: '', apiKey: '' },
      pacs: { enabled: false, endpoint: '', apiKey: '' }
    }
  },
  interface: {
    theme: 'light' as 'light' | 'dark' | 'auto',
    language: 'zh-CN',
    dateFormat: 'YYYY-MM-DD',
    timeFormat: 'HH:mm',
    currency: 'CNY',
    timezone: 'Asia/Shanghai',
    pageSize: 20,
    autoSave: true
  }
})

// 时间选择器数据
const workdayTime = ref<[Date, Date]>()
const weekendTime = ref<[Date, Date]>()

// 表单验证规则
const hospitalFormRef = ref()
const hospitalRules = {
  name: [{ required: true, message: '请输入医院名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入医院编码', trigger: 'blur' }],
  address: [{ required: true, message: '请输入医院地址', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
  email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }]
}

// 方法
const loadSettings = async () => {
  try {
    const settings = await settingsStore.getSystemSettings()
    Object.assign(settingsForm, settings)
    
    // 设置时间选择器的值
    setTimePickerValues()
  } catch (error) {
    ElMessage.error('加载设置失败')
  }
}

const setTimePickerValues = () => {
  // 转换时间格式给时间选择器
  const parseTime = (timeStr: string) => {
    const [hours, minutes] = timeStr.split(':')
    const date = new Date()
    date.setHours(parseInt(hours), parseInt(minutes), 0, 0)
    return date
  }

  workdayTime.value = [
    parseTime(settingsForm.business.workingHours.weekdays.start),
    parseTime(settingsForm.business.workingHours.weekdays.end)
  ]

  weekendTime.value = [
    parseTime(settingsForm.business.workingHours.weekends.start),
    parseTime(settingsForm.business.workingHours.weekends.end)
  ]
}

const handleSaveSection = async (section: string) => {
  loading.value = true
  try {
    // 更新工作时间
    if (section === 'business') {
      updateWorkingHours()
    }

    await settingsStore.updateSystemSettings(section as any, settingsForm[section as keyof typeof settingsForm])
    ElMessage.success('设置保存成功')
  } catch (error) {
    ElMessage.error('设置保存失败')
  } finally {
    loading.value = false
  }
}

const updateWorkingHours = () => {
  if (workdayTime.value) {
    settingsForm.business.workingHours.weekdays.start = formatTime(workdayTime.value[0])
    settingsForm.business.workingHours.weekdays.end = formatTime(workdayTime.value[1])
  }

  if (weekendTime.value) {
    settingsForm.business.workingHours.weekends.start = formatTime(weekendTime.value[0])
    settingsForm.business.workingHours.weekends.end = formatTime(weekendTime.value[1])
  }
}

const formatTime = (date: Date) => {
  return date.toTimeString().substr(0, 5)
}

const handleRefreshStatus = async () => {
  try {
    systemStatus.value = await settingsStore.getSystemStatus()
  } catch (error) {
    ElMessage.error('获取系统状态失败')
  }
}

const handleBackup = async () => {
  try {
    backupLoading.value = true
    const result = await settingsStore.backupSystemData()
    if (result.success) {
      ElMessage.success(`备份完成：${result.filename} (${result.size})`)
    }
  } catch (error) {
    ElMessage.error('备份失败')
  } finally {
    backupLoading.value = false
  }
}

const handleRestore = async () => {
  if (!selectedBackupFile.value) {
    ElMessage.warning('请选择备份文件')
    return
  }

  try {
    await ElMessageBox.confirm(
      '确定要恢复数据吗？此操作将覆盖当前数据！',
      '确认恢复',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    restoreLoading.value = true
    const result = await settingsStore.restoreSystemData(selectedBackupFile.value)
    if (result.success) {
      ElMessage.success('数据恢复完成')
      showRestoreDialog.value = false
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('数据恢复失败')
    }
  } finally {
    restoreLoading.value = false
  }
}

const handleCleanup = async () => {
  if (cleanupOptions.value.length === 0) {
    ElMessage.warning('请选择清理选项')
    return
  }

  try {
    await ElMessageBox.confirm(
      '确定要清理系统数据吗？',
      '确认清理',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    cleanupLoading.value = true
    const options = {
      cleanLogs: cleanupOptions.value.includes('logs'),
      cleanTempFiles: cleanupOptions.value.includes('temp'),
      cleanOldBackups: cleanupOptions.value.includes('backups'),
      daysToKeep: cleanupDays.value
    }

    const result = await settingsStore.cleanupSystemData(options)
    if (result.success) {
      ElMessage.success(`清理完成，释放空间：${result.details.spaceFreed}`)
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('清理失败')
    }
  } finally {
    cleanupLoading.value = false
  }
}

const handleTestEmail = async () => {
  emailTestLoading.value = true
  try {
    const result = await settingsStore.testEmailConfig(settingsForm.system.notifications.email)
    if (result.success) {
      ElMessage.success(result.message)
    } else {
      ElMessage.error(result.message)
    }
  } catch (error) {
    ElMessage.error('测试失败')
  } finally {
    emailTestLoading.value = false
  }
}

const handleTestSms = async () => {
  smsTestLoading.value = true
  try {
    const result = await settingsStore.testSmsConfig(settingsForm.system.notifications.sms)
    if (result.success) {
      ElMessage.success(result.message)
    } else {
      ElMessage.error(result.message)
    }
  } catch (error) {
    ElMessage.error('测试失败')
  } finally {
    smsTestLoading.value = false
  }
}

const handleExportSettings = async () => {
  try {
    const result = await settingsStore.exportSettings()
    if (result.success) {
      // 下载文件
      const blob = new Blob([result.data], { type: 'application/json' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = result.filename
      a.click()
      URL.revokeObjectURL(url)
      
      ElMessage.success('设置导出成功')
    }
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

const handleFileChange = (file: any) => {
  importFile.value = file.raw
}

const handleImportSettings = async () => {
  if (!importFile.value) {
    ElMessage.warning('请选择配置文件')
    return
  }

  importLoading.value = true
  try {
    const text = await importFile.value.text()
    const result = await settingsStore.importSettings(text)
    
    if (result.success) {
      ElMessage.success(result.message)
      showImportDialog.value = false
      await loadSettings()
    } else {
      ElMessage.error(result.message)
    }
  } catch (error) {
    ElMessage.error('导入失败')
  } finally {
    importLoading.value = false
  }
}

onMounted(() => {
  loadSettings()
  handleRefreshStatus()
})
</script>

<style lang="scss" scoped>
.settings-management {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  .page-title {
    font-size: 24px;
    font-weight: 600;
    color: #303133;
    margin: 0;
  }

  .header-actions {
    display: flex;
    gap: 12px;
  }
}

.status-cards {
  margin-bottom: 20px;

  .status-card {
    .status-content {
      display: flex;
      align-items: center;
      gap: 16px;

      .status-icon {
        width: 50px;
        height: 50px;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-size: 24px;

        &.server { background: #409EFF; }
        &.database { background: #67C23A; }
        &.resource { background: #E6A23C; }
        &.storage { background: #F56C6C; }
      }

      .status-info {
        .status-title {
          font-size: 14px;
          color: #909399;
          margin-bottom: 4px;
        }

        .status-value {
          font-size: 18px;
          font-weight: 600;
          margin-bottom: 4px;

          &.running {
            color: #67C23A;
          }

          &.stopped {
            color: #F56C6C;
          }
        }

        .status-detail {
          font-size: 12px;
          color: #909399;
        }
      }
    }
  }
}

.settings-card {
  min-height: 600px;

  .settings-tabs {
    :deep(.el-tabs__content) {
      padding: 20px;
    }
  }

  .settings-section {
    h3 {
      margin: 0 0 20px 0;
      color: #303133;
      font-weight: 600;
      border-bottom: 1px solid #e4e7ed;
      padding-bottom: 10px;
    }

    .el-form {
      max-width: 800px;
    }

    .el-divider {
      margin: 30px 0;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    text-align: center;

    .header-actions {
      width: 100%;
      justify-content: center;
      flex-wrap: wrap;
    }
  }

  .status-cards {
    :deep(.el-col) {
      margin-bottom: 16px;
    }
  }

  .settings-card {
    .settings-tabs {
      :deep(.el-tabs--left) {
        .el-tabs__header {
          float: none;
          margin-right: 0;
          margin-bottom: 20px;

          .el-tabs__nav-wrap {
            &::after {
              display: none;
            }
          }

          .el-tabs__nav {
            display: flex;
            flex-wrap: wrap;
          }
        }

        .el-tabs__content {
          padding: 0 10px;
        }
      }
    }
  }
}
</style>